import { Node } from "@tiptap/core";

const FileNode = Node.create({
  name: "graph",

  group: "block",
  selectable: true,
  atom: true,

  addAttributes() {
    return {
      src: {
        default: null,
        parseHTML: (element) => {
          // 从 style 背景或 data-src 中解析
          const bgImage = element.style?.backgroundImage;
          if (bgImage && bgImage.startsWith("url(")) {
            return bgImage.slice(4, -1).replace(/['"]/g, "");
          }
          return element.getAttribute("data-src") || null;
        },
      },
      text: {
        default: null,
        parseHTML: (element) => {
          const textEl = element.querySelector(".skc-text");
          return textEl ? textEl.textContent : null;
        },
      },
      id: {
        default: null,
        parseHTML: (element) => element.id || null,
      },
    };
  },

  parseHTML() {
    return [
      {
        tag: "div.skc-graph",
        getAttrs: (node) => {
          if (
            node &&
            node.nodeType === 1 &&
            node.tagName === "DIV" &&
            node.classList.contains("skc-graph")
          ) {
            // 尝试从 background-image 中提取 src
            const style = node.getAttribute("style") || "";
            const backgroundImageMatch = style.match(/background-image\s*:\s*url\(['"]?(.*?)['"]?\)/);
            const src = backgroundImageMatch ? backgroundImageMatch[1] : node.getAttribute("data-src");

            const textElement = node.querySelector(".skc-text");
            const text = textElement?.textContent?.trim();
            const id = node.id;

            if (src && text) {
              return { src, text, id };
            }
          }
          return false;
        },
      },
    ];
  },

  renderHTML({ HTMLAttributes }) {
    const { src, text, id } = HTMLAttributes;

    return [
      "div",
      {
        class: "skc-graph",
        id: id, // 添加 id 到这里
        style: `
          background-image: url(${src});
          background-size: contain;
          background-position: center;
          background-repeat: no-repeat;
          border-radius: 8px;
          min-height: 200px; /* 最小高度，确保背景可见 */
          position: relative;
        `,
      },
      // 文本层（避免被背景覆盖）
      [
        "div",
        { class: "skc-text-box", style: "position: relative; z-index: 1;" },
        ["span", { class: "skc-text" }, text],
      ],
    ];
  },
});

export default FileNode;
